package com.twohand.admin.Util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.twohand.admin.Entity.User;
import com.twohand.utils.Response.BaseException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;

@Component
public class JwtUtil {
    public static String slat;
    @Value("${custom.slat}")
    public void setSlat(String slat){
        JwtUtil.slat = slat;
    }
    public static String getToken(User user){
        Calendar instnce = Calendar.getInstance();
        instnce.add(Calendar.DATE,2);
        JWTCreator.Builder builder = JWT.create();
        builder.withClaim("username",user.getNickname())
                .withClaim("openid",user.getOpenid())
                .withClaim("id",user.getId());
        return builder.withExpiresAt(instnce.getTime())
                .sign(Algorithm.HMAC256(slat));
    }
    public static DecodedJWT decodeToken(String token){
        if(StringUtils.isEmpty(token)){
            throw new BaseException(401,"token不能为空");
        }
        JWTVerifier builder = JWT.require(Algorithm.HMAC256(slat)).build();

        return builder.verify(token);
    }

    public static User getCurrentUser(){
        HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("token");
        DecodedJWT decodedJWT =  JwtUtil.decodeToken(token);
        Integer id = decodedJWT.getClaim("id").asInt();
        String nickname = decodedJWT.getClaim("username").asString();
        String openid = decodedJWT.getClaim("openid").asString();
        User user = new User();
        user.setId(id);
        user.setNickname(nickname);
        user.setOpenid(openid);
        return user;
    }
}
